type Handler=(data?:any)=>void

class IEventPusher{
    private handlers:{[index:string]:Handler[]};
    static EVENT_PUBLISHER:IEventPusher;
    constructor(){
      this.handlers={};
    }
    public static getEventPublisher(){
        if(IEventPusher.EVENT_PUBLISHER==null){
            IEventPusher.EVENT_PUBLISHER=new IEventPusher();
        }
        return IEventPusher.EVENT_PUBLISHER;
    }

    on(type:string,handler:Handler){
       if(!(type in this.handlers)){
           this.handlers[type]=[];
       }
        this.handlers[type].push(handler);
        return this;
    }

    off(type:string,handler:Handler){
        if(!(type in this.handlers)){
             console.warn(`${type} not exist`);
            return;
        }
        this.handlers[type]=this.handlers[type].filter((item)=>{
             item!=handler;
        })
        return this;
    }

    emit(type:string,data?:any){
        if(!(type in this.handlers)){
             console.warn(`event type:${type} not exist`);
            return;
        }
        this.handlers[type].forEach((handler)=>{
             handler(data);
        })

    }
}


let iEventPublisher:IEventPusher=IEventPusher.getEventPublisher();

export default iEventPublisher;